/*
 * @Author: hongbin
 * @Date: 2021-11-12 19:52:19
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-19 09:22:15
 * @Description:查询collection数据
 */
import { PlayArrow } from "@mui/icons-material";
import { IconButton, TextField } from "@mui/material";
import { FC, ReactElement, useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import { DeepColourTitle } from "../CollectionSide";
import { Flex } from "../styled";
import Tags from "./Tags";
import ShowData from "./ShowData";
import { queryCollection } from "../../api/mongo";

interface IProps {
  selectedCollection: string;
  id: string;
}

export interface PayloadProps {
  collection: string;
  fetching: boolean;
  data?: any;
}

const DataTable: FC<IProps> = ({ selectedCollection, id }): ReactElement => {
  const [tags, setTags] = useState<{ [key: string]: PayloadProps }>({});
  const [active, setActive] = useState(selectedCollection);

  const getData = useCallback(
    selectedCollection => {
      let payload = tags[selectedCollection];
      if (!payload) {
        payload = { fetching: true, collection: selectedCollection };
        setTags(prev => ({ ...prev, [selectedCollection]: payload }));
        queryCollection({
          id,
          type: "mongo",
          collection: selectedCollection,
        }).then(result => {
          console.log(result);
          if (result.data) {
            payload.fetching = false;
            payload.data = result.data.list;
            setTags(prev => ({ ...prev, [selectedCollection]: payload }));
          }
        });
      }
      setActive(selectedCollection);
    },
    [id, tags]
  );

  useEffect(() => {
    getData(selectedCollection);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedCollection]);

  const toggleCollection = useCallback((collection: string) => {
    setActive(collection);
  }, []);

  const closeCollection = useCallback((collection: string) => {
    setActive("");
    setTags(prev => {
      const data = { ...prev };
      delete data[collection];
      return data;
    });
  }, []);

  const payload = tags[active];

  const handleDelete = (delId: string) => {
    payload.data = payload.data.filter(
      (item: { _id: string }) => item._id !== delId
    );
  };

  const handleUpdate = (updateId: string, newField: any) => {
    const index = payload.data.findIndex((item: any) => item._id === updateId);
    payload.data[index] = { ...payload.data[index], ...newField };
  };

  return (
    <Container>
      <Tags
        tags={Object.keys(tags)}
        active={active}
        onChangeTag={toggleCollection}
        onCloseTag={closeCollection}
      />
      {payload ? (
        <>
          <Flex style={{ margin: "0.5rem" }}>
            <TextField
              variant="outlined"
              size="small"
              InputProps={{
                startAdornment: (
                  <DeepColourTitle
                    style={{ width: "auto" }}
                  >{`db.${active}.`}</DeepColourTitle>
                ),
              }}
              style={{ width: "100%", marginRight: 20 }}
              defaultValue="find({}).sort({_id:-1}).limit(50)"
            />
            <IconButton
              size="large"
              edge="start"
              color="inherit"
              aria-label="run"
            >
              <PlayArrow />
            </IconButton>
          </Flex>
          <ShowData
            onDelete={handleDelete}
            onUpdate={handleUpdate}
            collection={active}
            payload={payload}
          />
        </>
      ) : null}
    </Container>
  );
};

export default DataTable;

const Container = styled.div`
  flex: 1;
  margin: 1rem;
  overflow: hidden;
  display: flex;
  flex-direction: column;
`;
